package cn.sc.summer.construction.sms;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import cn.sc.summer.constant.enums.StatusEnum;
import cn.sc.summer.constant.sms.SmsConstant;
import cn.sc.summer.constant.util.AssertUtil;
import cn.sc.summer.daoapi.dao.SmsTemplateMapper;
import cn.sc.summer.daoapi.po.SmsTemplate;
import cn.sc.summer.domain.sms.SmsTemplateService;
import cn.sc.summer.exception.enums.CommonExceptionEnum;
import cn.sc.summer.exception.exceptions.CommonException;
import cn.sc.summer.protocol.form.sms.SmsTemplateAddForm;
import cn.sc.summer.protocol.vo.SmsTemplateVO;
import cn.sc.summer.redis.util.RedisHelper;
import cn.sc.summer.sms.enums.SmsServerEnum;
import cn.sc.summer.sms.properties.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 类名：短信模板实现业务层
 *
 * @author a-xin
 * @date 2023/12/15 16:57
 */
@Slf4j
@Service
public class SmsTemplateServiceImpl implements SmsTemplateService {

    @Resource
    private SmsTemplateMapper smsTemplateMapper;

    @Resource
    private SmsProperties smsProperties;

    /**
     * 添加短信模版
     *
     * @param form 模板信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SmsTemplateVO addTemplate(SmsTemplateAddForm form) {

        SmsServerEnum smsServerEnum = Optional.ofNullable(SmsServerEnum.getByType(form.getServer()))
                .orElseThrow(() -> new CommonException("不存在对应的模板信息！"));
        Long typeCount = smsTemplateMapper.selectCount(new LambdaQueryWrapper<SmsTemplate>()
                .eq(SmsTemplate::getType, form.getType().toUpperCase())
                .eq(SmsTemplate::getServer, smsServerEnum.getInfo()));
        CommonExceptionEnum.NORMAL_EXCEPTION.exceptionIf(typeCount > 0,
                "该平台: " + smsServerEnum.getInfo() + "已存在类型为: " + form.getType() + "的短信模板！");

        Long idCount = smsTemplateMapper.selectCount(new LambdaQueryWrapper<SmsTemplate>()
                .eq(SmsTemplate::getTemplateId, form.getTemplateId())
                .eq(SmsTemplate::getServer, smsServerEnum.getInfo()));
        CommonExceptionEnum.NORMAL_EXCEPTION.exceptionIf(idCount > 0,
                "该平台: " + smsServerEnum.getInfo() + "已存在模版ID为: " + form.getTemplateId() + "的短信模板！");

        SmsTemplate smsTemplate = new SmsTemplate();
        smsTemplate.setId(IdWorker.getIdStr());
        smsTemplate.setTemplateId(form.getTemplateId());
        smsTemplate.setType(form.getType().toUpperCase());
        smsTemplate.setTempDesc(form.getTempDesc());
        smsTemplate.setServer(smsServerEnum.getInfo());
        smsTemplate.setDel(StatusEnum.ENABLE_OR_NOT_DELETED.getType());
        smsTemplateMapper.insert(smsTemplate);

        AssertUtil.functionIf(StrUtil.isBlank(smsProperties.getEnabled()) && smsProperties.getEnabled().equals(form.getServer()), () -> {
            RedisHelper.hSet(SmsConstant.SMS_TEMPLATE + smsTemplate.getType(), SmsConstant.SMS_TEMPLATE_ID, smsTemplate.getTemplateId());
            RedisHelper.hSet(SmsConstant.SMS_TEMPLATE + smsTemplate.getType(), SmsConstant.SMS_TEMPLATE_DESC, smsTemplate.getTempDesc());
        });

        return BeanUtil.toBean(smsTemplate, SmsTemplateVO.class);
    }

    /**
     * 删除短信模板
     *
     * @param id 模板ID
     */
    @Override
    public void deleteTemplate(String id) {
        Optional.ofNullable(smsTemplateMapper.selectById(id))
                .ifPresent(smsTemplate -> {
                    smsTemplateMapper.deleteById(id);
                    AssertUtil.functionIf(RedisHelper.hHasKey(SmsConstant.SMS_TEMPLATE + smsTemplate.getType(), smsTemplate.getTemplateId()),
                            () -> RedisHelper.del(SmsConstant.SMS_TEMPLATE + smsTemplate.getType()));
                });
    }

    /**
     * 获取短信模版信息
     *
     * @param server 模版平台信息
     * @return 模版信息
     */
    @Override
    public List<SmsTemplateVO> getTemplate(String server) {
        List<SmsTemplate> smsTemplates = smsTemplateMapper.selectList(new LambdaQueryWrapper<SmsTemplate>()
                .eq(StrUtil.isNotBlank(server), SmsTemplate::getServer, server));
        return AssertUtil.functionIfPre(smsTemplates, CollUtil::isNotEmpty, () -> smsTemplates.stream()
                .map(smsTemplate -> BeanUtil.toBean(smsTemplate, SmsTemplateVO.class))
                .collect(Collectors.toList()), new ArrayList<>());
    }

}
